package com.amoyt.project.domain.bo;

import com.amoyt.project.domain.pojo.User;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

// 忽略类中未定义的字段（如 "password"）
@JsonIgnoreProperties(ignoreUnknown = true)
public class LoginUser implements UserDetails, Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 存储自定义用户信息
     */
    private User user;

    /**
     * 存储用户拥有的权限标识
     */
    private List<String> permissions;

    public LoginUser() {
    }

    // 构造方法传入用户和权限
    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    /**
     * 存储SpringSecurity所需要的权限信息的集合
     */
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private List<SimpleGrantedAuthority> authorities;

    //用来返回Security所需的权限信息
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        //如果已经有权限
        if(authorities!=null){
            return authorities;
        }

        //为空 则把permissions中String类型的权限信息封装成SimpleGrantedAuthority对象
        authorities = new ArrayList<>(); //懒汉模式，必须new出来
        for(String permission : permissions){
            SimpleGrantedAuthority authority=new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }
        return authorities;
    }

    // 完善其他方法实现
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true; // 根据实际业务判断
    }

    @Override
    public boolean isAccountNonLocked() {
        return "0".equals(user.getStatus()); // 0表示正常
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return 0 == user.getDeleted(); // 0表示未删除
    }

    //setter和getter

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<String> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<String> permissions) {
        this.permissions = permissions;
    }

    @Override
    public String toString() {
        return "LoginUser{" +
                "user=" + user +
                ", permissions=" + permissions +
                ", authorities=" + authorities +
                '}';
    }
}